class Transaction < ActiveRecord::Base
  belongs_to :seller, :class_name => 'User'
  has_and_belongs_to_many :buyers, :class_name => 'User'
  belongs_to :ad, :class_name => 'Ad'
  belongs_to :adtype, :class_name => 'Adtype'

  def initialize(params=nil)
    if params
      params['seller'] = User.current
      params['ad'] = Ad.find_by_label(params['ad'])
      params['adtype'] = Adtype.find(1)

      buyers = []
        for username in params[:buyers].split(',')
        buyers << User.find_by_username(username.strip)
      end
      params[:buyers] = buyers
    end
    super
  end

  def save
    if sum
      self.seller.credit(self.sum)
      self.buyers.each do |buyer|
        buyer.debit(self.sum / self.buyers.size)
      end
    end
    self.ad.disable! if self.ad
    AdsMailer.deliver_transaction_confirmation(@ad, self.seller, self.buyers)
    super
  end
end
